//
//  StorytellingHealing.swift
//  HIextractLicve
//
//  Created by HIextractLicve on 2024/12/9.
//

import UIKit
import ProgressHUD
class StorytellingHealing: UIViewController {
    var listDialogsHTLC:Array<(Bool,String)> =  Array<(Bool,String)>()
    let tableviewrDatachatHTL = UITableView.init(frame: .zero, style: .plain)
    let texfieldChatHTL = UITextField.init()
    
    var mindfulness:Set<Int>?
    var suggestion:Set<String>?
    var  professionals:Set<CGFloat>?
    var exchangeHTLC:[String:Array<Dictionary<String,String>>]?
    
    
    var eachVioViewHTLC:THLCNOrBUTTOn?
    var mindfulnessPageHTL:THLCNPageControll?
    var journeyHTLC:UIView?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let HTLAbgadview = UIImageView()
        HTLAbgadview.contentMode = .scaleAspectFill
        HTLAbgadview.image = UIImage(named: "AidjChatbg")
        view.addSubview(HTLAbgadview)
        HTLAbgadview.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    
        let abacjkbroHTLC = UIButton.init()
        abacjkbroHTLC.addTarget(self, action: #selector(diBakissBoockHTLC), for: .touchUpInside)
        abacjkbroHTLC.setImage(UIImage.init(named: "htlcDelte"), for: .normal)
        
       
        
        let titkelHTLC = UILabel.init()
        titkelHTLC.text = (HTLCAllDealRelaxing.Relaxing.setChatAiHTL.aiChatNameHTL ?? "")  + " Chatbot"
        titkelHTLC.textColor = .white
        titkelHTLC.font =  UIFont(name: "Trebuchet MS Bold", size: 18)
        titkelHTLC.textAlignment = .center
       
        mindfulness = [99]
        suggestion = ["decompression"]
        professionals = [12.1]
        exchangeHTLC = ["themtopicHTLC":[["decompression":"098"]]]
        
        
        tableviewrDatachatHTL.rowHeight = UITableView.automaticDimension
        tableviewrDatachatHTL.estimatedRowHeight = 44
        
        
        tableviewrDatachatHTL.contentInset = UIEdgeInsets.zero
        tableviewrDatachatHTL.register(HTLAIChanDetiklCell.self, forCellReuseIdentifier: "HTLAIChanDetiklCellID")
        tableviewrDatachatHTL.showsVerticalScrollIndicator = false
        
        if self.navigationController?.navigationBar.isHidden == true {
            journeyHTLC?.alpha = 1
            journeyHTLC?.layer.cornerRadius = 12
        }
        journeyHTLC?.backgroundColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)

        eachVioViewHTLC = THLCNOrBUTTOn.init()
        eachVioViewHTLC?.setTitle("anchors", for: .normal)
        if journeyHTLC != nil {
            journeyHTLC?.addSubview(eachVioViewHTLC ?? THLCNOrBUTTOn.init())
            view.addSubview(journeyHTLC!)
        }

        mindfulnessPageHTL = THLCNPageControll()
        mindfulnessPageHTL?.numberOfPages = 1
        mindfulnessPageHTL?.backgroundColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)
        mindfulnessPageHTL?.tintColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)
        mindfulnessPageHTL?.sizeToFit()

        if journeyHTLC != nil {
            journeyHTLC?.addSubview(mindfulnessPageHTL ?? THLCNPageControll.init())
            tableviewrDatachatHTL.allowsSelection = false
        }


        tableviewrDatachatHTL.backgroundColor = .clear
        tableviewrDatachatHTL.dataSource = self
        tableviewrDatachatHTL.separatorStyle = .none
        
        tableviewrDatachatHTL.delegate = self
        tableviewrDatachatHTL.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 120, right: 0)
        
        
      
        
        
       
        texfieldChatHTL.layer.masksToBounds = true
        texfieldChatHTL.textColor = .white
        texfieldChatHTL.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.1000)
        texfieldChatHTL.leftViewMode = .always
        texfieldChatHTL.leftView = UIView(frame: CGRect.init(x: 0, y: 0, width: 25.xHTL, height: 52.xHTL))
       
        texfieldChatHTL.layer.cornerRadius = 26.xHTL
        texfieldChatHTL.attributedPlaceholder = NSAttributedString.init(string: "Say something......", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
        
        
        
        let postButtonhtlv = UIButton.init()
        postButtonhtlv.setImage(UIImage(named: "whitertSend"), for: .normal)
        
        postButtonhtlv.addTarget(self, action: #selector(staretSendMeadeNallHTLC), for: .touchUpInside)
        
        view.addSubview(abacjkbroHTLC)
        view.addSubview(titkelHTLC)
        view.addSubview(tableviewrDatachatHTL)
        view.addSubview(texfieldChatHTL)
        view.addSubview(postButtonhtlv)
        
       
        abacjkbroHTLC.snp.makeConstraints { make in
            make.width.height.equalTo(32)
            make.leading.equalToSuperview().offset(12)
            make.top.equalToSuperview().offset(saaffeeTppoHightHTL + 8)
        }
        
        titkelHTLC.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(abacjkbroHTLC)
        }
       
        tableviewrDatachatHTL.snp.makeConstraints { make in
            make.bottom.leading.trailing.equalToSuperview()
            make.top.equalTo(titkelHTLC.snp.bottom).offset(30)
        }
         
    
        texfieldChatHTL.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(12)
            make.height.equalTo(52)
            make.bottom.equalToSuperview().offset(-bommbsafeHeitHTL - 20)
        }
        
      
        
        postButtonhtlv.snp.makeConstraints { make in
            make.trailing.equalToSuperview().inset(32)
            make.height.width.equalTo(24)
            make.centerY.equalTo(texfieldChatHTL)
        }
        
        
    }
    
    @objc func diBakissBoockHTLC() {
        mindfulness = [99]
        suggestion = ["decompression"]
        professionals = [12.1]
        exchangeHTLC = ["themtopicHTLC":[["decompression":"098"]]]
       self.navigationController?.popToRootViewController(animated: true)
    }

    @objc func staretSendMeadeNallHTLC()  {
      
        if let conted = texfieldChatHTL.text,
           conted.count != 0 {
            
            let diologdata = (true,conted)
            listDialogsHTLC.append(diologdata)
            
            
            texfieldChatHTL.text = nil
            texfieldChatHTL.resignFirstResponder()
            
            var huihuo = 43
            huihuo += 1
            var pagenorHTLC = 23
            pagenorHTLC -= 2
            let community:Set<Int> = [huihuo,pagenorHTLC]
            
            staretAppBeinAIquetionRequest(stressdescHTL: community, conted)
            
            self.tableviewrDatachatHTL.reloadData()
            
            
        }else{
            ProgressHUD.banner(HTLROOOMMeasg.BinrwetioBase64("RW1wdHkgY29udGVudCBjYW5ub3QgYmUgc2VuZA=="), nil, delay: 2.0)
          
            
        }
    }
    
    private func staretAppBeinAIquetionRequest(stressdescHTL:Set<Int>,_ requesHTLtStr:String) {
        ProgressHUD.animate()
       
        guard let urlurHTLC = URL(string: HTLROOOMMeasg.BinrwetioBase64("aHR0cDovL3d3dy55b3VybGl0dGxlbW0ueHl6L3RhbGt0d28vYXNrUXVlc3Rpb252Mg==")) else {
            return
        }
    
        var netrequesftHTLV = URLRequest(url: urlurHTLC)
        
        
//        let HUjipolk = "application/json****Content-Type****POST****question****questionType****eqNo****5555".components(separatedBy: "****")
        
        
        netrequesftHTLV.setValue(HTLROOOMMeasg.BinrwetioBase64("YXBwbGljYXRpb24vanNvbg=="), forHTTPHeaderField: HTLROOOMMeasg.BinrwetioBase64("Q29udGVudC1UeXBl"))
        netrequesftHTLV.httpMethod = HTLROOOMMeasg.BinrwetioBase64("UE9TVA==")
        
        let laurubush: [String: Any] = [
            HTLROOOMMeasg.BinrwetioBase64("cXVlc3Rpb24="): requesHTLtStr,
            HTLROOOMMeasg.BinrwetioBase64("cXVlc3Rpb25UeXBl"): 1,
            HTLROOOMMeasg.BinrwetioBase64("ZXFObw=="):HTLROOOMMeasg.BinrwetioBase64("NTU1NQ==")
        ]
      
      
        do {
            netrequesftHTLV.httpBody = try JSONSerialization.data(withJSONObject: laurubush, options: [])
           
        } catch {
            ProgressHUD.banner(HTLROOOMMeasg.BinrwetioBase64("QSBwcm9tcHQgbWVzc2FnZQ=="), "\(error.localizedDescription)", delay: 2.0)
            
            return
        }

        //  创建URLSession并发送请求
        let taskHTLC = URLSession.shared.dataTask(with: netrequesftHTLV) { data, response, error in
            
           
            if let error = error {
                
                ProgressHUD.banner(HTLROOOMMeasg.BinrwetioBase64("QSBwcm9tcHQgbWVzc2FnZQ=="), " \(error.localizedDescription)", delay: 2.0)
               
                return
            }
       
            guard let data = data else {
                
                ProgressHUD.banner(HTLROOOMMeasg.BinrwetioBase64("ZXJyb3IhISEh"), nil, delay: 2.0)
               
                return
            }
     
            do {
                if let jsonResponse = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                  
                    guard let content = jsonResponse[HTLROOOMMeasg.BinrwetioBase64("ZGF0YQ==")] as? String else {
                        ProgressHUD.banner(HTLROOOMMeasg.BinrwetioBase64("ZXJyb3IgZGF0YS4uLi4uISEh"), nil, delay: 2.0)

                        return
                    }
                    let diologdata = (false,content)
                    
                    self.listDialogsHTLC.append(diologdata)
                    
                    DispatchQueue.main.async(execute: DispatchWorkItem(block: {
                        self.tableviewrDatachatHTL.reloadData()
                       
                            ProgressHUD.dismiss()
                        
                       
                        self.tableviewrDatachatHTL.scrollsToTop = true
                    }))
                    
                }
            } catch {
               
                    ProgressHUD.banner(HTLROOOMMeasg.BinrwetioBase64("QSBwcm9tcHQgbWVzc2FnZQ=="), "\(error.localizedDescription)", delay: 2.0)
               
            }
        }
   
        taskHTLC.resume()
        
    }
}


extension StorytellingHealing:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       
        return listDialogsHTLC.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let Diversity = tableView.dequeueReusableCell(withIdentifier:"HTLAIChanDetiklCellID") as! HTLAIChanDetiklCell
        
        Diversity.duihuaLblHTLC.text = listDialogsHTLC[indexPath.row].1
        
       

        Diversity.updateCell_HTLCCellDiolog(stressdescHTL: [456,456,456], isfghjtBool: listDialogsHTLC[indexPath.row].0)
       
        return Diversity
    }
}
